package com.firefighting.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.firefighting.entity.ProprietorConnector;
import com.firefighting.service.ProprietorConnectorService;

@Controller
@RequestMapping("ConnectorController")
public class ProprietorConnectorController
{
	@Autowired
	private ProprietorConnectorService proprietorConnectorService;
	
	/**
	 * @author zhyan
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonGenerationException 
	 * @function 查询所有的业主联系人
	 * @date 2018.6.8
	 */
	@RequestMapping("queryAllProprietorConnector")
	private String queryAllProprietorConnector(HttpServletRequest request, Model model) throws JsonGenerationException, JsonMappingException, IOException
	{
		@SuppressWarnings("rawtypes")
		List<HashMap> content = proprietorConnectorService.queryAllProprietorConnector();
		ObjectMapper objectMapper = new ObjectMapper();
		
		model.addAttribute("content", objectMapper.writeValueAsString(content));//查询成功
		return "";
	}
	
	/**
	 * @author zhyan
	 * @function 根据id查询业主联系人
	 * @date 2018.6.8
	 */
	@RequestMapping("queryProprietorConnector")
	private String queryProprietorConnector(HttpServletRequest request, Model model)
	{
		int id = Integer.parseInt(request.getParameter("id"));
		ProprietorConnector connector = proprietorConnectorService.queryProprietorConnectorById(id);
		
		model.addAttribute("content", connector);
		return "";
	}
	
	/**
	 * @author zhyan
	 * @function 删除业主联系人
	 * @date 2018.6.8
	 * @return
	 */
	@RequestMapping("deleteProprietorConnector")
	private String deleteProprietorConnector(HttpServletRequest request, Model model)
	{
		int id = Integer.parseInt(request.getParameter("id"));
		int number = proprietorConnectorService.deleteProprietorConnector(id);
		
		if(number > 0)
		{
			model.addAttribute("message", "true");//删除成功
		}
		else
		{
			model.addAttribute("message", "false");//删除失败
		}
		
		return "";
	}
	
	/**
	 * @author zhyan
	 * @throws ParseException 
	 * @throws IOException 
	 * @throws IllegalStateException 
	 * @function 添加业主联系人
	 * @date 2018.6.8
	 */
	@RequestMapping("addProprietorConnector")
	private String addProprietorConnector(MultipartFile file, HttpServletRequest request, Model model) throws ParseException, IllegalStateException, IOException
	{
		int proprietorId = Integer.parseInt(request.getParameter("proprietorId"));
		String identify = request.getParameter("identify");
		String name = request.getParameter("name");
		String sex = request.getParameter("sex");
		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
		java.sql.Date birth = new java.sql.Date(sdf.parse(request.getParameter("birth")).getTime());
		String department = request.getParameter("department");
		String position = request.getParameter("position");
		String mobilePhone = request.getParameter("mobilePhone");
		String email = request.getParameter("email");
		String qq = request.getParameter("qq");
		String wechat = request.getParameter("wechat");
		String technicalLevel = request.getParameter("technicalLevel");
		String identificationCard = request.getParameter("identificationCard");
		
		String path = request.getSession().getServletContext().getRealPath("upload");
		String fileName = file.getOriginalFilename();//获取文件名
		File dir = new File(path, fileName);
		
		if (!dir.exists())
		{
			dir.mkdirs();
		}
		// MultipartFile自带的解析方法
		file.transferTo(dir);
		String certificatePicture = dir.toString();
		
		ProprietorConnector record = new ProprietorConnector();
		record.setProprietorId(proprietorId);
		record.setIdentify(identify);
		record.setName(name);
		record.setSex(sex);
		record.setBirth(birth);
		record.setDepartment(department);
		record.setPosition(position);
		record.setMobilePhone(mobilePhone);
		record.setEmail(email);
		record.setQq(qq);
		record.setWechat(wechat);
		record.setTechnicalLevel(technicalLevel);
		record.setIdentificationCard(identificationCard);
		record.setCertificatePicture(certificatePicture);
		
		int number = proprietorConnectorService.insertProprietorConnector(record);
		if(number >  0)
		{
			model.addAttribute("message","true");//添加成功
		}
		else
		{
			model.addAttribute("message", "false");//添加失败
		}
		
		return "";
	}
	
	/**
	 * @author zhyan
	 * @throws ParseException 
	 * @throws IOException 
	 * @throws IllegalStateException 
	 * @function 根据id修改业主联系人表信息
	 * @date 2018.6.8
	 */
	@RequestMapping("editProprietorConnector")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
	private String editProprietorConnector(MultipartFile file, HttpServletRequest request, Model model) throws ParseException, IllegalStateException, IOException
	{
		int id = Integer.parseInt(request.getParameter("id"));
		ProprietorConnector record = proprietorConnectorService.queryProprietorConnectorById(id);
		
		int proprietorId = Integer.parseInt(request.getParameter("proprietorId"));
		String identify = request.getParameter("identify");
		String name = request.getParameter("name");
		String sex = request.getParameter("sex");
		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
		java.sql.Date birth = new java.sql.Date(sdf.parse(request.getParameter("birth")).getTime());
		String department = request.getParameter("department");
		String position = request.getParameter("position");
		String mobilePhone = request.getParameter("mobilePhone");
		String email = request.getParameter("email");
		String qq = request.getParameter("qq");
		String wechat = request.getParameter("wechat");
		String technicalLevel = request.getParameter("technicalLevel");
		String identificationCard = request.getParameter("identificationCard");
		
		String path = request.getSession().getServletContext().getRealPath("upload");
		String fileName = file.getOriginalFilename();//获取文件名
		File dir = new File(path, fileName);
		
		if (!dir.exists())
		{
			dir.mkdirs();
		}
		// MultipartFile自带的解析方法
		file.transferTo(dir);
		String certificatePicture = dir.toString();
		
		record.setProprietorId(proprietorId);
		record.setIdentify(identify);
		record.setName(name);
		record.setSex(sex);
		record.setBirth(birth);
		record.setDepartment(department);
		record.setPosition(position);
		record.setMobilePhone(mobilePhone);
		record.setEmail(email);
		record.setQq(qq);
		record.setWechat(wechat);
		record.setTechnicalLevel(technicalLevel);
		record.setIdentificationCard(identificationCard);
		record.setCertificatePicture(certificatePicture);
		
		int number = proprietorConnectorService.updateProprietorConnector(record);
		if(number > 0)
		{
			model.addAttribute("message", "true");//更新成功
		}
		else
		{
			model.addAttribute("message", "false");
		}
		
		return "";
	}
	
	/**
	 * @author zhyan
	 * @function 图片上传功能
	 * @date 2018.6.8
	 * @TIPS 仿网格化代码完成
	 */
	@RequestMapping("uploadPicture")
	private String uploadPicture(MultipartFile file, HttpServletRequest request, Model model) throws IllegalStateException, IOException
	{
		int id = Integer.parseInt(request.getParameter("id"));
		String path = request.getSession().getServletContext().getRealPath("upload");
		String fileName = file.getOriginalFilename();//获取文件名
		File dir = new File(path, fileName);
		
		if (!dir.exists())
		{
			dir.mkdirs();
		}
		// MultipartFile自带的解析方法
		file.transferTo(dir);
		
		String certificatePicture = dir.toString();
		ProprietorConnector record = proprietorConnectorService.queryProprietorConnectorById(id);
		record.setCertificatePicture(certificatePicture);
		int number = proprietorConnectorService.updateProprietorConnector(record);
		
		if(number > 0)
		{
			model.addAttribute("message", "true");//上传成功，将路径写入数据库
		}
		else
		{
			model.addAttribute("message", "false");//上传失败
		}
		
		return "";
	}
	
	/**
	 * @author zhyan
	 * @function 下载图片
	 * @date 2018.6.8
	 * @TIPS：仿网格化项目代码完成
	 */
	@RequestMapping("/down")
	public void down(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		int id = Integer.parseInt(request.getParameter("id"));
		ProprietorConnector record = proprietorConnectorService.queryProprietorConnectorById(id);
		
		try
		{
			// 从数据库中获取凭证的完整文件路径
			String filePath = record.getCertificatePicture();
			
			// 获取输入流
			InputStream bis = new BufferedInputStream(new FileInputStream(new File(filePath)));
			// 获取文件名称
			String temp[] = filePath.replaceAll("\\\\", "/").split("/");
			String fileName = "";
			
			if (temp.length > 1)
			{
				fileName = temp[temp.length - 1];

			}
			
			// 设置文件下载头
			response.addHeader("Content-Disposition","attachment;filename=" + fileName);
			// 设置文件ContentType类型，这样设置，会自动判断下载文件类型
			response.setContentType("multipart/form-data");
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			int len = 0;
			
			while((len = bis.read()) != -1)
			{
				out.write(len);
				out.flush();
			}
			bis.close();
			out.close();
		}
		catch (Exception e)
		{
			response.sendRedirect(request.getContextPath() + "/Revise/toOrderExport");
		}
	}
	
}